package org.sdsc.crms.entity.security;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "CRMS_DEPT")
public class Dept {

	private Long id;
	private String name;
	private Long indexs;
	private String manager;
	private String description;
	private Dept parentDept;
	private Set<Dept> childDepts = new LinkedHashSet<Dept>();

	@Id
	@GeneratedValue(generator = "deptGenerator")
	@GenericGenerator(name = "deptGenerator", strategy = "sequence", parameters = { @Parameter(name = "sequence", value = "SEQ_DEPT") })
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getIndexs() {
		return indexs;
	}

	public void setIndexs(Long indexs) {
		this.indexs = indexs;
	}

	public String getManager() {
		return manager;
	}

	public void setManager(String manager) {
		this.manager = manager;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "PARENT_ID")
	public Dept getParentDept() {
		return parentDept;
	}

	public void setParentDept(Dept parentDept) {
		this.parentDept = parentDept;
	}

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parentDept")
	public Set<Dept> getChildDepts() {
		return childDepts;
	}

	public void setChildDepts(Set<Dept> childDepts) {
		this.childDepts = childDepts;
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public String fromListToJsonString(List<Dept> deptList) {
		String json = "";
		StringBuffer jsonString = new StringBuffer(json);
		jsonString.append("[\n");
		for (Dept dept : deptList) {
			jsonString.append("{ attributes: { id: '" + dept.getId() + "' }, ");
			if (dept.getChildDepts().size() > 0) {
				jsonString.append("state: 'closed', ");
			}
			jsonString.append("data: '" + dept.getName() + "' },\n");
		}
		int lastIndex = jsonString.lastIndexOf(",");
		json = jsonString.toString().substring(0, lastIndex) + "\n]";
		return json;
	}
}
